import time

from libs.account import Account
from libs.log import Log
import random
from libs.window import AdsWindow
from libs.task_helper import TaskHelper
from selenium.webdriver.common.by import By
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC
from selenium.webdriver.common.action_chains import ActionChains
import sys


def random_sleep(min=2, max=5):
    time.sleep(random.randint(min, max))

def wait_for_element(locator, timeout=10):
    try:
        element = WebDriverWait(driver, timeout).until(
            EC.presence_of_element_located((locator))
        )
        return element
    except Exception as e:
        return None

if __name__ == "__main__":
    parser = TaskHelper.default_args_parser('Social Account')
    args = parser.parse_args()
    task_helper = TaskHelper.from_args(args)

    user_id = args.user_id

    log = Log(user_id)
    log.info('social_account_activate_start')
    account = Account()

    try:
        # 打开Gmail
        driver = AdsWindow(user_id).open(False)
        action = ActionChains(driver)

        log.debug('gmail:start')
        driver.get("https://mail.google.com/mail/u/0/#inbox")
        mail_list = wait_for_element((By.XPATH, "//table[@role='grid']"))
        if mail_list is None:
            account.save_email(user_id, 'open_fail')
            log.info('gmail: open failed')
        else:
            title = driver.title
            email = title.split(' - ')[1]
            account.save_email(user_id, email)

            unread_emails = driver.find_elements(By.XPATH, "//tr[@class='zA zE']")
            log.info(f'gmail:unread_emails: {len(unread_emails)}')
            random_sleep(5, 10)
            for _ in range(5):
                try:
                    email = wait_for_element((By.XPATH, "//tr[@class='zA zE']"))
                    if email is None:
                        break
                    email.click()  # 点击未读邮件
                    back_button = wait_for_element((By.XPATH, "//div[@class='ar6 T-I-J3 J-J5-Ji']"), 30)
                    if back_button:
                        log.debug('gmail: read')
                        random_sleep(2, 5)
                        driver.back()
                    else:
                        log.debug('gmail: email open fail')
                    random_sleep(2, 5)
                except Exception as e:
                    log.debug(f'gmail: read fail, {str(e)}')
                    break

        log.debug('gmail:end')

        # 打开Discord
        log.debug(f'discord: start')
        driver.get("https://discord.com/channels/@me")
        random_sleep(2, 5)
        # 关闭弹窗
        close_button = wait_for_element((By.XPATH, "//svg[@class='closeIcon_f9a4c9']"), 5)
        if close_button is not None:
            close_button.click()
        name_elem = wait_for_element((By.CSS_SELECTOR, '.title_b97bdb'), 2)
        if name_elem is not None:
            account.save_discord(user_id, f"{name_elem.text}")
        random_sleep(5, 10)
        log.debug('discord:end')

        # 打开X
        log.debug('x:start')
        driver.get("https://x.com")
        profile_button = wait_for_element((By.XPATH, "//a[@aria-label='Profile']"), 5)
        if profile_button:
            profile_href = profile_button.get_attribute('href')
            account.save_twitter(user_id, '@' + profile_href.split("/")[-1])
        else:
            account.save_twitter(user_id, 'open_failed')
        home_button = wait_for_element((By.XPATH, "//a[@href='/home']"), 5)
        if home_button is None:
            log.info('x: open failed')
        else:
            home_button.click()

            # 继续滚动主页
            end_time = time.time() + 15
            while time.time() < end_time:
                driver.execute_script("window.scrollBy(0, 500);")  # 每次向下滚动500像素
                time.sleep(random.uniform(1, 3))  # 随机等待1到3秒

        # 等待通知按钮可见
        try:
            # 查找通知按钮（使用 data-testid 来准确定位）
            notification_button = wait_for_element((By.XPATH, "//a[@data-testid='AppTabBar_Notifications_Link']"),
                                                   10)

            if notification_button is None:
                log.info('x: open fail')
            else:
                # 获取 aria-label 的值来判断是否有未读通知
                aria_label = notification_button.get_attribute("aria-label")
                random_sleep(2, 5)
                # 如果 aria-label 中包含 "unread notifications"，表示有未读通知
                if "unread notifications" in aria_label:
                    # 点击通知按钮
                    notification_button.click()

                    # 浏览未读通知，滚动一下
                    end_time_notifications = time.time() + 10
                    while time.time() < end_time_notifications:
                        driver.execute_script("window.scrollBy(0, 500);")
                        random_sleep(2, 5)

                    # 回到主页
                    home_button = WebDriverWait(driver, 10).until(
                        EC.element_to_be_clickable((By.XPATH, "//a[@href='/home']"))
                    )
                    home_button.click()
                else:
                    log.debug("x:no unread notifications")

        except Exception as e:
            log.debug(f'x: fail, {str(e)}')

        log.debug('x:end')
    except Exception as e:
        raise e
    finally:
        log.info('social_account_activate_end')
